<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
          :delFunc="handleDelete" :page-change="changePage" :currentPage="searchParam.pageNum" :editFunc="handleEdit" :refresh="() => {searchParam.pageNum =1; getData()}">
          <template #toolbarBtn>
              <el-button type="warning" :icon="CirclePlusFilled" @click="openDialog(false)">新增</el-button>
          </template>
          <template #operatorBtn="{row}">
            <el-button size="small" type="primary" :icon="Edit" @click="modifyPwd(row)">修改密码</el-button>
          </template>
      </TableCustom>
    </div>
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
        :close-on-click-modal="false" @close="closeDialog">
        <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :add="addData" :update="updateData" />
    </el-dialog>
    <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData"></TableDetail>
    </el-dialog>
    <el-dialog title="修改密码" v-model="visible2" width="700px" destroy-on-close>
      <el-form ref="formRef" :model="passwordForm" :label-width="120">
        <el-form-item label="旧密码" prop="oPwd" :rules="[{required: true, message: '请输入旧密码', trigger: 'blur'}]">
          <el-input v-model="passwordForm.oPwd" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="nPwd" :rules="[{required: true, message: '请输入新密码', trigger: 'blur'}]">
          <el-input v-model="passwordForm.nPwd" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="cPwd" :rules="[{required: true, message: '请输入确认密码', trigger: 'blur'}]">
          <el-input v-model="passwordForm.cPwd" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="savePwd(formRef)">保存</el-button>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { FormOption, FormOptionList } from '@/types/form-option';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import TableSearch from '@/components/table-search.vue';
import TableCustom from '@/components/table-custom.vue';
import TableEdit from '@/components/table-edit.vue';
import TableDetail from '@/components/table-detail.vue';
import { DoctorService } from '@/api/service/doctorService'
import { decryptPassword } from '@/utils/crypto'
import { Edit } from '@element-plus/icons-vue';

const query = reactive({
  name: null,
  tel: null,
  account: null,
});
const searchParam = reactive({
  pageNum: 1,
  pageSize: 10,
  params: query
})
const searchOpt = ref<FormOptionList[]>([
  {type: 'input', label: '康复师', prop: 'name' },
  {type: 'input', label: '联系电话', prop: 'tel' },
  {type: 'input', label: '登录账号', prop: 'account' },
])
// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '康复师', prop: 'name', required: true },
        { type: 'input', label: '联系电话', prop: 'tel', required: true },
        { type: 'input', label: '登录账号', prop: 'account', required: true },
        { type: 'input', label: '密码', prop: 'password', required: true, hide: true },
    ]
})
const passwordForm = reactive({
  oPwd: null,
  nPwd: null,
  cPwd: null
})
const handleSearch = () => {
  getData();
};

const rowData = ref({});
const isEdit = ref(false);
let columns = ref([
  { type: 'index', label: '序号', width: 120, align: 'center' },
  { prop: 'name', label: '康复师',span:24 },
  { prop: 'tel', label: '联系电话',span:24 },
  { prop: 'account', label: '登录账号',span:24 },
  { prop: 'operator', label: '操作', width: 420 },
])
const page = reactive({
    index: 1,
    size: 10,
    total: 0,
})
const tableData = ref([]);
const visible = ref(false)
const openDialog = (val: boolean) => {
  isEdit.value = val
  visible.value = true
};
// 查看详情弹窗相关
const visible1 = ref(false);

const viewData = ref({
    row: {},
    list: []
});
const handleView = (row) => {
    viewData.value.row = { ...row }
    viewData.value.list = columns.value.filter((_,i) => i !=0 && i!= columns.value.length -1);
    visible1.value = true
};
const handleDelete = async (row) => {
  console.log('del',row.id)
    const res = await DoctorService.delete(row.id)
    ElMessage.success('删除成功');
    getData();
};
const handleEdit = (row) => {
    rowData.value = { ...row };
    if(rowData.value.password?.length > 0) {
      rowData.value.password = decryptPassword(rowData.value.password)
    }
    openDialog(true)
};
const changePage = (val: number) => {
    searchParam.pageNum = val;
    getData();
};
const getData = async ()=> {
  const res = await DoctorService.page(searchParam)
  tableData.value = res.list;
  page.total = res.total;
}
getData();
const addData = async (val: any) => {
  const result = await DoctorService.create(val)
    closeDialog();
    getData();
};
const updateData = async (val: any) => {
  const result = await DoctorService.update(val)
    closeDialog();
    getData();
};
const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

const visible2 = ref(false);
let originPwd = ref(null);
let doctorRow = reactive({});
const modifyPwd = (row) => {
const { password }  = row
  doctorRow = row
  originPwd.value = decryptPassword(password)
  console.log('originPwd.value==',originPwd.value)
  visible2.value = true
}
const formRef = ref<FormInstance>();
const savePwd =  (formEl: FormInstance | undefined) => {
  if (!formEl) return;
	formEl.validate( async (valid) => {
		if (!valid) return false;
		if(passwordForm.oPwd != originPwd.value){
      return ElMessage.warning('旧密码不正确请重新确认')
    }
    if(passwordForm.nPwd != passwordForm.cPwd){
      return ElMessage.warning('确认密码不一致请重新确认')
    }
    doctorRow.password = passwordForm.nPwd
    console.log('doctorRow=',doctorRow)
    const result = await DoctorService.update(doctorRow)
    visible2.value = false;
    ElMessage.success('密码修改成功')
    formRef.value.resetFields();
    getData();
	});
}
</script>